package com.horizon.wxapp.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.horizon.wxapp.dao.CartsMapper;
import com.horizon.wxapp.dao.GoodMapper;
import com.horizon.wxapp.entity.Carts;
import com.horizon.wxapp.service.CartsService;
import com.horizon.wxapp.service.GoodService;
import com.horizon.wxapp.vo.UserCarts;
import org.apache.catalina.User;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class CartServiceImpl implements CartsService {

    @Resource
    private CartsMapper cartsMapper;
    @Resource
    private GoodService goodService;

    @Override
    public void updateCart(Carts carts) {
        cartsMapper.update(carts, new LambdaQueryWrapper<Carts>().eq(Carts::getId, carts.getId()));
    }

    @Override
    public void deleteCartById(Integer id) {
        cartsMapper.deleteById(id);
    }

    @Override
    public List<UserCarts> selectCarts(String userName, String tel) {
        LambdaQueryWrapper<Carts> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Carts::getUsername, userName)
                .eq(Carts::getTel, tel);
        List<Carts> carts = cartsMapper.selectList(queryWrapper);
        List<UserCarts> result = new ArrayList<>();
        for (Carts cart : carts) {
            UserCarts vo = new UserCarts();
            BeanUtils.copyProperties(cart, vo);
            vo.setGood(goodService.getGoodById(cart.getGoodId()));
            result.add(vo);
        }
        return result;
    }

    @Override
    public Carts selectOne(String userName, String tel, Integer goodId) {
        LambdaQueryWrapper<Carts> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Carts::getUsername, userName)
                .eq(Carts::getTel, tel)
                .eq(Carts::getGoodId, goodId);
        Carts cart = cartsMapper.selectOne(queryWrapper);
        System.out.println(cart);
        return cart;
    }

    @Override
    public void addCart(Carts cart) {
        cartsMapper.insert(cart);
    }
}
